<?php

namespace app\admin\controller\admin;

use app\admin\controller\Admin;
use app\common\Constants;
use app\common\ErrorCode;
use app\common\exception\BusinessException;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class Tool extends Admin
{


    public function cleanCache(): \think\response\Json
    {
        try {
            $post = $this->request->post();
            $cache_key = $post['cache_key'];
            if (in_array('cache', $cache_key)) {
                Cache::clear();
            }
            if (in_array('log', $cache_key)) {
                Db::name('admin_log')->delete(true);
            }
            if (in_array('runtime', $cache_key)) {
                $runtimePath = app()->getRuntimePath();
                $result = delete_dir_recursively($runtimePath, false);
                if (!$result) {
                    throw new BusinessException(Constants::E_SYS_CACHE_ERROR, ErrorCode::E_SYS_CACHE_ERROR);
                }
            }
            return $this->success();
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     *  清理系统删除的数据
     * @return \think\response\Json
     */
    public function clearSysDeletedData(): \think\response\Json
    {
        try {
            // 配置要处理的表前缀
            $prefixes = ['ra_admin_', 'ra_dev_'];
            $results = []; // 存储删除结果

            // 获取所有表名
            $tables = Db::query("SHOW TABLES");

            // 提取表名数组
            $tableNames = array_map('current', $tables);

            // 处理所有符合条件的表
            foreach ($tableNames as $table) {
                // 检查表前缀是否符合要求
                foreach ($prefixes as $prefix) {
                    if (strpos($table, $prefix) === 0) {
                        // 处理单张表
                        $results[$table] = $this->processTable($table);
                        break; // 匹配到一个前缀即可
                    }
                }
            }

            return $this->success(['data' => $results]);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 删除当前应用中的日志文件
     * @return \think\response\Json|array
     */
    public function clearRuntimeLogs(): \think\response\Json|array
    {
        try {
            $successCount = 0;  // 成功删除计数
            $failCount = 0;     // 删除失败计数

            // 构建日志目录路径（如：runtime/admin/log/）
            $logDir = runtime_path() . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR;

            // 检查日志目录是否存在
            if (!is_dir($logDir)) {
                throw new ValidateException('日志目录不存在');
            }

            // 获取所有年月子目录（如：202505）
            $yearMonthDirs = glob($logDir . '*', GLOB_ONLYDIR);

            foreach ($yearMonthDirs as $yearMonthDir) {
                // 获取该月份目录中的所有日志文件
                $logFiles = glob($yearMonthDir . DIRECTORY_SEPARATOR . '*.log');

                foreach ($logFiles as $logFile) {
                    // 删除文件并统计结果
                    if (@unlink($logFile)) {
                        $successCount++;
                    } else {
                        $failCount++;
                    }
                }
            }

            // 返回统计结果
            $data = [
                'success' => $successCount,
                'fail' => $failCount
            ];
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->success(['data' => $data]);
    }

    private function processTable($table): array
    {
        try {
            $fields = Db::getFields($table);
            if (!array_key_exists('delete_time', $fields)) {
                return [
                    'status' => 'skipped',
                    'reason' => 'No delete_time field on this table',
                    'deleted' => 0
                ];
            }

            // 获取待删除数据量
            $count = Db::table($table)->whereNotNull('delete_time')->count();
            if ($count == 0) {
                return [
                    'status' => 'skipped',
                    'reason' => 'No soft deleted records',
                    'deleted' => 0
                ];
            }
            // 执行物理删除
            $deleted = Db::table($table)->whereNotNull('delete_time')->delete();
            return [
                'status' => 'success',
                'soft_delete_field' => 'delete_time',
                'deleted' => $deleted
            ];

        } catch (\Exception $e) {
            throw $e;
        }
    }
}